package com.puppet.redistest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;

import java.time.Duration;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

@SpringBootTest
public class Demo1 {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate redisTemplate2;
    @Test
    //测试字符串类型
    public void testString(){
        //得到字符串类型操作对象
        ValueOperations ops = redisTemplate2.opsForValue();
        //存储数据
        ops.set("cit","12");
        //获取数据
        System.out.println(ops.get("cit"));
    }
    //写入Book对象
    @Test
    public void testBook() {
        //得到操作字符串类型的对象
        ValueOperations ops = redisTemplate.opsForValue();
        Book book = new Book(1, "西游记", 28.56d, "人民出版社", LocalDate.now(), "吴承恩");
        //添加键和值，并且只保存5分钟
        ops.set("book:1", book, Duration.ofMinutes(5));
        //取出数据
        book = (Book) ops.get("book:1");
        System.out.println("book对象：" + book);
    }
    //测试hash类型
    @Test
    public void testHash() {
        //创建一个hash类型的工具类
        HashOperations ops = redisTemplate.opsForHash();
        //添加多个元素
        ops.put("car:100", "name", "凯迪拉克");
        ops.put("car:100", "price", 300000d);
        ops.put("car:100", "color", "黑色");
        //获取一个字段数据
        String name = (String) ops.get("car:100", "name");
        System.out.println("车名：" + name);
        //获取所有的字段和值
        Map<Object, Object> map = ops.entries("car:100");
        System.out.println("所有的字段和值：" + map);
        //所有的键
        Set<String> keys = ops.keys("car:100");
        System.out.println("所有的键：" + keys);
        //所有的值
        List<Object> values = ops.values("car:100");
        System.out.println("所有的值：" + values);
    }

    //List类型
    @Test
    public void testList() {
        //获取操作列表的对象
        ListOperations ops = redisTemplate.opsForList();
        Book book1 = new Book(1, "西游记", 28.56d, "人民出版社", LocalDate.now(), "吴承恩");
        Book book2 = new Book(2, "红楼梦", 35.20d, "人民文学出版社", LocalDate.now(), "曹雪芹");
        Book book3 = new Book(3, "三国演义", 30.80d, "上海古籍出版社", LocalDate.now(), "罗贯中");
        //添加多个元素到列表中
        // jdk 9 以上才有的api 	List.of(book1, book2, book3)
       // Long rows = ops.leftPushAll("book:list", List.of(book1, book2, book3));
        Long rows = ops.leftPushAll("book:list", Arrays.asList(book1, book2, book3));
        // jdk 8 使用的api 	 Arrays.asList(book1,book2,book3)
        ops.leftPushAll("book:list", Arrays.asList(book1,book2,book3));
        System.out.println("添加了" + rows + "个元素");
        //获取所有的元素
        List<Book> list = ops.range("book:list", 0, -1);
        list.forEach(System.out::println);
        //删除最左边的元素
        Book book = (Book) ops.leftPop("book:list");
        System.out.println("删除的元素是：" + book);

    }
}
